package com.example.cloud.demo.controller;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.service.annotation.GetExchange;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${eureka.instance.metadata-map.env}")
    private String env;

    @Value("${eureka.instance.metadata-map.version}")
    private String version;

    @GetMapping
    public ResponseEntity<String> createOrder() {
        String orderId = UUID.randomUUID().toString();
        ResponseEntity<String> entity = restTemplate.getForEntity("http://PAYMENT/payment/" + orderId, String.class);
        log.info("Payment result {} by {}", entity.getBody(), orderId);
        return entity;
    }
    
    @GetMapping("/services")
    public ResponseEntity<Map<String, Object>> getService() {
        Map<String, Object> map = new HashMap<>();
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            List<Map<String, String>> list = new ArrayList<>();
            for (ServiceInstance instance : instances) {
                Map<String, String> m = new HashMap<>();
                m.put("host", instance.getHost());
                m.put("port", String.valueOf(instance.getPort()));
                m.put("instanceId", instance.getInstanceId());
                m.put("uri", instance.getUri().toString());
                m.put("metadata", JSON.toJSONString(instance.getMetadata()));
                list.add(m);
            }
            map.put(service, list);
        }
        map.put("currentEnv", Map.of("env", env, "version", version));
        return ResponseEntity.ok(map);
    }

}
